package com.yax.yapi.mainmethod;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yax.yapi.plug.ClassPathClassLoader;
import com.yax.yapi.plug.PlugIntf;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.io.*;
import java.util.*;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;


public class Form extends Application {
    private static final Set<String> blackList=new HashSet<>();
    public static  Map<String,String> keyValueMap=new HashMap<>();
    private PlugIntf plugIntf;
    private static Stage stageNew=null;
    public static Map<String, String> getKeyValueMap() {
        return keyValueMap;
    }
    private static Logger log = Logger.getLogger("Form");
    public static ExecutorService pool = Executors.newFixedThreadPool(3);
    private static final String version= "1.4.2";
    private static  Properties properties=null;
    private static  String propertiesPath;
    private static  String plugClassPath;
    static {
        blackList.add("sqlForPage");
        blackList.add("minRow");
        blackList.add("shardname");
        blackList.add("maxRow");
        blackList.add("pageSize");
        blackList.add("page");
        pool.execute(()->{keyValueMap=readFileMap("C:yapi公共字典.txt");});
    }
    @Override
    public void start(Stage primaryStage) throws Exception {

        primaryStage.setTitle("Yapi登陆 版本"+version);
        primaryStage.setResizable(true);
        primaryStage.getIcons().add(new Image(Objects.requireNonNull(Form.class.getClassLoader().getResourceAsStream("images/favicon.png"))));

        primaryStage.setOnCloseRequest(event -> {
            pool.shutdownNow();
        });
        /*Platform.setImplicitExit(false);
        BufferedImage image = ImageIO.read(Objects.requireNonNull(Form.class.getClassLoader().getResourceAsStream("images/favicon.png")));
        TrayIcon trayIcon = new TrayIcon(image, "yapi");
        trayIcon.setImageAutoSize(true);
        SystemTray tray = SystemTray.getSystemTray();
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    Platform.runLater(() -> {
                        if (primaryStage.isIconified()) {
                            primaryStage.setIconified(false);
                        }
                        if (!primaryStage.isShowing()) {
                            primaryStage.show();
                        }
                        primaryStage.toFront();
                    });
                }
                else if (e.getButton() == MouseEvent.BUTTON3) {
                    Platform.setImplicitExit(true);
                    tray.remove(trayIcon);
                    Platform.runLater(primaryStage::close);
                }
            }
        });
        tray.add(trayIcon);*/


        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));


        Text scenetitle = new Text("Welcome");
        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        grid.add(scenetitle, 0, 0, 2, 1);

        String pwStr=readFileString(YapiUtil.getExepath()+"config.json");
        JSONObject pwJsonTemp=new JSONObject();
        if(pwStr!=null&&!"".equals(pwStr)){
            try {
                pwJsonTemp = JSONObject.parseObject(pwStr);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        Label userName = new Label("姓 名:");
        grid.add(userName, 0, 1);

        TextField userTextField = new TextField();
        String ln=pwJsonTemp.getString("loginname");
        String pwS=pwJsonTemp.getString("password");
        String url=pwJsonTemp.getString("url");
        String xls=pwJsonTemp.getString("xlsPath");
        String plugClassName=pwJsonTemp.getString("plugClassName");
         plugClassPath=pwJsonTemp.getString("plugClassPath");
        if(plugClassPath!=null&&!"".equals(plugClassPath)) {
            ClassPathClassLoader classLoader = new ClassPathClassLoader(plugClassPath);
            Class pluginClass =classLoader.getPluginClass();
            plugIntf = (PlugIntf) (pluginClass==null?classLoader.loadClass(plugClassName):pluginClass).newInstance();
        }
         propertiesPath=pwJsonTemp.getString("properties");
        properties=getProperties(propertiesPath);
        if(url!=null&&!"".equals(url)){
            YapiUtil.setYapiUrl(url);
        }
        if(ln!=null&&!"".equals(ln)){
            userTextField.setText(ln.trim());
        }
        if(xls!=null&&!"".equals(xls)){
            ExcelUtils.setXlsPath(xls);
        }
        grid.add(userTextField, 1, 1,2,1);

        Label pw = new Label("密 码:");
        grid.add(pw, 0, 2);

        PasswordField pwBox = new PasswordField();
        if(pwS!=null&&!"".equals(pwS)){
            pwBox.setText(pwS.trim());
        }
        grid.add(pwBox, 1, 2,2,1);


        CheckBox cb = new CheckBox();
        cb.setText("记住密码");
        cb.setSelected(true);
        grid.add(cb, 0, 4);

        Button btnImport = new Button("导入公共字典");
        HBox hbBtnImport = new HBox(10);
        hbBtnImport.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtnImport.getChildren().add(btnImport);
        grid.add(hbBtnImport, 1, 4);

        btnImport.setOnAction(e -> {
            // 创建新的stage
            if(stageNew==null) {
                stageNew = new Stage();
            }
            stageNew.setResizable(false);
            stageNew.setOnCloseRequest(event -> {
                stageNew.close();
                stageNew=null;
            });
            stageNew.setTitle("导入公共字典");
            stageNew.getIcons().add(new Image(Objects.requireNonNull(Form.class.getClassLoader().getResourceAsStream("images/favicon.png"))));
            GridPane secondPane = new GridPane();
            Scene secondScene = new Scene(secondPane, 500, 500);
            TextArea textAreaTemp=new TextArea();
            textAreaTemp.setPrefSize(500,480);;
            textAreaTemp.setEditable(true);
            secondPane.add(textAreaTemp, 0, 0,5,5);
            Button btnimport = new Button("导入");
            btnimport.setPrefWidth(500);
            HBox hbBtnimport = new HBox(100);
            hbBtnimport.setAlignment(Pos.BOTTOM_CENTER);
            hbBtnimport.setPrefWidth(500);
            hbBtnimport.getChildren().add(btnimport);
            secondPane.add(hbBtnimport, 0, 5,5,1);
            btnimport.setOnAction(e1->{
                String source=textAreaTemp.getText().trim();
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("yapi返回");
                alert.setHeaderText(null);
                try {
                    Map<String,String> data = YapiUtil.analysis(source);
                    writeFileMap("C:yapi公共字典.txt", data);
                    alert.setContentText("导入成功");
                    textAreaTemp.clear();
                }catch (Exception ex){
                    ex.printStackTrace();
                    alert.setContentText("导入失败 请去查看日志!!!");
                }
                alert.showAndWait();
            });
            stageNew.setScene(secondScene);
            stageNew.show();
        });

        Button btn = new Button("登 陆");
        HBox hbBtn = new HBox(10);
        hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtn.getChildren().add(btn);
        grid.add(hbBtn, 2, 4);

        final Text actiontarget = new Text();
        grid.add(actiontarget, 1, 6);

        btn.setOnAction(e -> {
            Map<String,String> result=YapiUtil.loginYapi(userTextField.getText(),pwBox.getText());
            if(result.size()==0){
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("yapi返回");
                alert.setHeaderText(null);
                alert.setContentText("登陆失败!!! 请检查网络连接是否正常或url地址是否配置正确");
                alert.showAndWait();
            }
            String res=result.get("response");
            JSONObject resJson=JSONObject.parseObject(res);
            int errcode=resJson.getInteger("errcode");
            String errmsg=resJson.getString("errmsg");
            if(errcode!=0){
                actiontarget.setFill(Color.FIREBRICK);
                actiontarget.setText(errmsg+"!!!");
                return;
            }
            if(cb.isSelected()){
                JSONObject pwJson=new JSONObject();
                pwJson.put("loginname",userTextField.getText());
                pwJson.put("password",pwBox.getText());
                pwJson.put("url",YapiUtil.getYapiUrl());
                pwJson.put("xlsPath",ExcelUtils.getXlsPath());
                pwJson.put("properties",propertiesPath);
                pwJson.put("plugClassName",plugClassName);
                pwJson.put("plugClassPath",plugClassPath);
                writeFileString(YapiUtil.getExepath()+"config.json",pwJson.toJSONString());
            }
            JSONObject userInfo=resJson.getJSONObject("data");
            String username=userInfo.getString("username");
            String cookie=result.get("Cookie");

            primaryStage.setTitle("构建Yapi 版本"+version);
            primaryStage.setScene(createMenuScene(username,cookie,userTextField.getText(),pwBox.getText()));

        });

        Scene scene = new Scene(grid, 350, 275);
        primaryStage.setScene(scene);
        primaryStage.show();
        pool.execute(()->{
            //检查更新
            checkVersion(primaryStage);
        });

    }

    private Scene createMenuScene(String username,String cookie,String loginname,String password){
        Group root = new Group();
        double width=720;
        double height=500;
        if(plugIntf!=null){
            width =plugIntf.width();
            height=plugIntf.height();
        }
        Scene scene = new Scene(root, width, height, Color.WHITE);

        scene.setOnDragOver(value->{
            value.acceptTransferModes(TransferMode.ANY);
        });
        scene.setOnDragDropped(value->{
            Dragboard dragboard = value.getDragboard();
            if (dragboard.hasFiles()) {
                try {
                    File file = dragboard.getFiles().get(0);
                    if (file != null) {
                        String path = file.getPath();
                        if (path.endsWith(".jar")) {
                            JSONObject pwJson = new JSONObject();
                            pwJson.put("loginname",loginname);
                            pwJson.put("password",password);
                            pwJson.put("url",YapiUtil.getYapiUrl());
                            pwJson.put("xlsPath",ExcelUtils.getXlsPath());
                            pwJson.put("properties",propertiesPath);
                            pwJson.put("plugClassPath", path);
                            pwJson.put("plugClassName", "");
                            writeFileString(YapiUtil.getExepath() + "config.json", pwJson.toJSONString());
                            Alert confirm = new Alert(Alert.AlertType.CONFIRMATION);
                            confirm.setTitle("yapi提醒");
                            confirm.setHeaderText("");
                            confirm.setContentText("是否重启软件加载插件");
                            Optional<ButtonType> buttonType = confirm.showAndWait();
                            String downLoad = System.getProperty("user.dir");
                            String fileName = "yapi-" + version + ".exe";
                            String exeAddress = System.getProperty("exe4j.moduleName");
                            if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) {
                                Thread thread = new Thread(() -> {
                                    try {
                                        Runtime.getRuntime().exec(downLoad + "\\" + fileName + " " + exeAddress);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    System.exit(0);
                                });
                                thread.start();
                            } else {
                            }
                        }
                        if(path.endsWith(".xlsx")){
                            JSONObject pwJson = new JSONObject();
                            pwJson.put("loginname",loginname);
                            pwJson.put("password",password);
                            pwJson.put("url",YapiUtil.getYapiUrl());
                            pwJson.put("xlsPath",path);
                            pwJson.put("properties",propertiesPath);
                            pwJson.put("plugClassPath", plugClassPath);
                            pwJson.put("plugClassName", "");
                            writeFileString(YapiUtil.getExepath() + "config.json", pwJson.toJSONString());
                            Alert confirm = new Alert(Alert.AlertType.CONFIRMATION);
                            confirm.setTitle("yapi提醒");
                            confirm.setHeaderText("");
                            confirm.setContentText("是否重启加载配置");
                            Optional<ButtonType> buttonType = confirm.showAndWait();
                            String downLoad = System.getProperty("user.dir");
                            String fileName = "yapi-" + version + ".exe";
                            String exeAddress = System.getProperty("exe4j.moduleName");
                            if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.OK_DONE)) {
                                Thread thread = new Thread(() -> {
                                    try {
                                        Runtime.getRuntime().exec(downLoad + "\\" + fileName + " " + exeAddress);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    System.exit(0);
                                });
                                thread.start();
                            } else {
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
        });




        TabPane tabPane = new TabPane();
        BorderPane borderPane = new BorderPane();
        List<Tab> tabs=new ArrayList<>();
        Tab tab1 = new Tab();
        tab1.setText("迁移yapi");
        tab1.setClosable(false);
        tab1.setContent(createTransferWindow(username,cookie));
        tabs.add(tab1);
        Tab tab2 = new Tab();
        tab2.setText("新增yapi");
        tab2.setClosable(false);
        tab2.setContent(createAddedWindow(username, cookie));
        tabs.add(tab2);
        if(plugIntf!=null){
            plugIntf.buildTabs(username,cookie,tabs);
        }
        for (Tab tab:tabs) {
            tabPane.getTabs().add(tab);
        }
        tabPane.setSide(Side.TOP);

        borderPane.prefHeightProperty().bind(scene.heightProperty());
        borderPane.prefWidthProperty().bind(scene.widthProperty());
        borderPane.setCenter(tabPane);
        root.getChildren().add(borderPane);
        return scene;

    }
    private ScrollPane createTransferWindow(String username,String cookie){
        Map<String, Object> componentMap=new ConcurrentHashMap<>();
        GridPane grid = new GridPane();
        grid.setMinSize(100,100);
        grid.setAlignment(Pos.TOP_LEFT);
        grid.setHgap(5);
        grid.setVgap(5);
        grid.setPadding(new Insets(10, 10, 10, 10));

        Label targetId = new Label("Ids(,分割)||catId");
        targetId.setPrefWidth(100);
        grid.add(targetId, 0, 0);

        Label targetgroupName = new Label("groupName");
        targetgroupName.setPrefWidth(100);
        grid.add(targetgroupName, 1, 0);

        Label targetproject = new Label("project");
        targetproject.setPrefWidth(100);
        grid.add(targetproject, 2, 0);

        Label targetmenu = new Label("menu");
        targetmenu.setPrefWidth(100);
        grid.add(targetmenu, 3, 0);

        TextField targetIdField = new TextField();
        targetIdField.setPrefWidth(100);
        grid.add(targetIdField, 0, 1,1,1);
        componentMap.put("Ids(,分割)||catId",targetIdField);

        TextArea textAreaLog=new TextArea();
        JSONObject  groupJson=YapiUtil.listGroup(cookie);
        JSONArray jsonArray=groupJson.getJSONArray("data");
        Map<String,String> groupMap=new HashMap<>();
        for(Object obj:jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            String group_name = jsonObject.getString("group_name");
            String _id=jsonObject.getString("_id");
            groupMap.put(group_name,_id);
        }
        ComboBox<Map.Entry<String,String>> targetgroupNameCb = new ComboBox(FXCollections.observableArrayList(groupMap.entrySet()));
        targetgroupNameCb.autosize();
        targetgroupNameCb.setPrefWidth(154);
        //数据转换
        targetgroupNameCb.setConverter(new StringConverter<Map.Entry<String,String>>() {
            //只显示名字
            @Override
            public String toString(Map.Entry<String,String> entry) {
                String value=null;
                if(entry!=null) {
                    value = entry.getKey();
                }
                return value;
            }

            @Override
            public Map.Entry<String,String>  fromString(String string) {
                String value=groupMap.get(string);
                return new Map.Entry<String, String>() {
                    @Override
                    public String getKey() {
                        return string;
                    }

                    @Override
                    public String getValue() {
                        return value;
                    }

                    @Override
                    public String setValue(String value) {
                        return value;
                    }
                };
            }
        });
        grid.add(targetgroupNameCb, 1, 1,1,1);
        componentMap.put("groupName",targetgroupNameCb);

        ComboBox targetProjectCb = new ComboBox();
        targetProjectCb.setPrefWidth(154);
        targetProjectCb.autosize();
        grid.add(targetProjectCb, 2, 1,1,1);
        componentMap.put("project",targetProjectCb);



        ComboBox targetMenuCb = new ComboBox();
        targetMenuCb.setPrefWidth(154);
        targetMenuCb.autosize();
        grid.add(targetMenuCb, 3, 1,1,1);
        componentMap.put("menu",targetMenuCb);

        Map<String,String> projectMap=new HashMap<>();
        targetgroupNameCb.setOnAction(e->{
            pool.execute(()->{
                projectMap.clear();
                JSONObject  projectJson=YapiUtil.listProject(cookie,targetgroupNameCb.getValue().getValue());
                JSONArray jsonArray1=projectJson.getJSONObject("data").getJSONArray("list");
                for(Object obj1:jsonArray1) {
                    JSONObject jsonObject = (JSONObject) obj1;
                    String name = jsonObject.getString("name");
                    String project_id=jsonObject.getString("_id");
                    projectMap.put(name,project_id);
                }
                Platform.runLater(()->{
                    targetProjectCb.setItems(FXCollections.observableArrayList(projectMap.keySet().toArray()));
                    targetProjectCb.getSelectionModel().select(0);
                });
            });
        });

        Map<String,String> menuMap=new HashMap<>();
        targetProjectCb.setOnAction(e->{
            pool.execute(()-> {
                menuMap.clear();
                if (targetProjectCb.getValue() != null) {
                    String projectId = targetProjectCb.getValue().toString();
                    JSONObject menuJson = YapiUtil.listMenu(cookie, projectMap.get(projectId));
                    JSONArray jsonArray2 = menuJson.getJSONArray("data");
                    for (Object obj2 : jsonArray2) {
                        JSONObject jsonObject = (JSONObject) obj2;
                        String name = jsonObject.getString("name");
                        String catid = jsonObject.getString("_id");
                        menuMap.put(name, catid);
                    }
                    Platform.runLater(() -> {
                        targetMenuCb.setItems(FXCollections.observableArrayList(menuMap.keySet().toArray()));
                        targetMenuCb.getSelectionModel().select(0);
                    });
                }
            });
        });

        Label pathLabel = new Label("最新路径(单个有效):");
        pathLabel.setPrefWidth(110);
        grid.add(pathLabel, 0, 2);
        TextField newPathField = new TextField();
        newPathField.setPrefWidth(208);
        grid.add(newPathField, 1, 2,2,1);
        componentMap.put("最新路径(单个有效):",newPathField);

        CheckBox isAddNew = new CheckBox();
        isAddNew.setText("是否自动批量更新path");
        isAddNew.setSelected(false);
        grid.add(isAddNew, 3, 2,1,1);
        componentMap.put("是否自动批量更新path",isAddNew);


        Button btnTransfer = new Button("迁移");
        btnTransfer.setPrefWidth(700);
        HBox hbBtnTransfer = new HBox(100);
        hbBtnTransfer.setAlignment(Pos.BOTTOM_CENTER);
        hbBtnTransfer.setPrefWidth(700);
        hbBtnTransfer.getChildren().add(btnTransfer);
        grid.add(hbBtnTransfer, 0, 3,4,1);
        componentMap.put("迁移",btnTransfer);
        btnTransfer.setOnAction(e -> {
            pool.execute(()->{
                try {
                    String id = targetIdField.getText();
                    String catId=null;
                    if(id.contains("cat_")){
                        catId=id.substring(4);
                    }
                    String project = projectMap.get(targetProjectCb.getValue().toString());
                    String menu = menuMap.get(targetMenuCb.getValue().toString());
                    String newPath=newPathField.getText();
                    String[] ids=new String[]{id};
                    if(id.contains(",")) {
                        ids = id.split(",");
                    }
                    if(id.contains("，")){
                        ids=id.split("，");
                    }
                    if(catId!=null&&!"".equals(catId)){
                        JSONObject  jsonObject =YapiUtil.listCat(cookie,catId);
                        log.info("返回值"+jsonObject);
                        JSONObject data=jsonObject.getJSONObject("data");
                        JSONArray list= data.getJSONArray("list");
                        ids=new String[list.size()];
                        int i=0;
                        for(Object obj:list){
                            JSONObject json= (JSONObject) obj;
                            String _id=json.getString("_id");
                            ids[i++]=_id;
                        }
                    }
                    log.info("要迁移的目标id "+Arrays.asList(ids));
                    newPath=ids.length==1?newPath:null;
                    List<String> idList=Arrays.asList(ids);
                    if(plugIntf!=null){
                        plugIntf.transferIdHandle(username,cookie,idList,componentMap);
                    }
                    for(String idTemp:idList){
                        JSONObject tempApiInfo = YapiUtil.transferYapi(componentMap,plugIntf,cookie, project, menu, idTemp, isAddNew.isSelected(),newPath,properties);
                        try {
                            /*int errcode = tempApiInfo.getInteger("errcode");
                            if (errcode == 40022) {
                                tempApiInfo = YapiUtil.transferYapi(cookie, project, menu, idTemp, true);
                            }*/
                            log.info(tempApiInfo.toJSONString());
                            JSONObject apiInfo = tempApiInfo;
                            int errcodeFinal = apiInfo.getInteger("errcode");

                            Platform.runLater(() -> {
                                textAreaLog.appendText("迁移Yapi结果: " + ((errcodeFinal == 0) ? "成功" : "失败") + "    id:" + idTemp + " ---> group:" + targetgroupNameCb.getValue().getKey() + ", project:" + targetProjectCb.getValue().toString() + ", menu:" + targetMenuCb.getValue().toString() + "  result:" + apiInfo.toJSONString() + "\r\n");
                            });
                        }catch (Exception ex){
                            ex.printStackTrace();
                            JSONObject finalTempApiInfo = tempApiInfo;
                            Platform.runLater(() -> {
                                textAreaLog.appendText("迁移Yapi发生未知异常: " + finalTempApiInfo.toJSONString()+"\r\n"+printThrowable(ex));
                            });
                        }
                    }
                }catch (Exception ex){
                    ex.printStackTrace();
                    Platform.runLater(() -> {
                        textAreaLog.appendText("迁移Yapi发生未知异常: " +printThrowable(ex));
                    });
                }
            });
        });

        Button riskManage = new Button("生成风控");
        riskManage.setPrefWidth(750);
        HBox hbBtnRiskManage = new HBox(100);
        hbBtnRiskManage.setAlignment(Pos.BOTTOM_CENTER);
        hbBtnRiskManage.setPrefWidth(750);
        hbBtnRiskManage.getChildren().add(riskManage);
        grid.add(hbBtnRiskManage, 0, 4,3,1);
        componentMap.put("生成风控",riskManage);

        CheckBox isEntry = new CheckBox();
        isEntry.setText("是否entry接口");
        isEntry.setSelected(true);
        grid.add(isEntry, 3, 4,1,1);
        componentMap.put("是否entry接口",isEntry);


        riskManage.setOnAction(action->{
            pool.execute(()->{
                String id = targetIdField.getText();
                int entry=isEntry.isSelected()?0:1;
                List<String> idList=new ArrayList<>();
                if(id==null||"".equals(id)){
                    String menu = menuMap.get(targetMenuCb.getValue().toString());
                    JSONObject  jsonObject =YapiUtil.listCat(cookie,menu);
                    log.info("返回值"+jsonObject);
                    JSONObject data=jsonObject.getJSONObject("data");
                    JSONArray list= data.getJSONArray("list");
                    for(Object obj:list){
                        JSONObject json= (JSONObject) obj;
                        String _id=json.getString("_id");
                        idList.add(_id);
                    }
                }else{
                    idList.addAll(Arrays.asList(id.split(",")));
                }
                Platform.runLater(() -> {
                    textAreaLog.appendText("风控SQL:\r\n");
                });
                for(String idTemp:idList){
                    try {
                        JSONObject jsonObject = YapiUtil.getApi(cookie, idTemp);
                        JSONObject data = jsonObject.getJSONObject("data");
                        String path = data.getString("path").split("/")[1];
                        String riskAddress = "未知风控路径";
                        String markdown = data.getString("markdown");
                        String[] risks = markdown.split("[\\s\\n]");
                        for (String temp : risks) {
                            String risk = temp.trim();
                            if (risk.contains("-") && risk.startsWith("com.zl.")) {
                                riskAddress = risk;
                                break;
                            }
                        }
                        String finalRiskAddress=riskAddress;
                        Platform.runLater(() -> {
                            textAreaLog.appendText("delete from pub_gateway_service where servicekey='" + path + "';\r\n");
                            textAreaLog.appendText("INSERT INTO `pub_gateway_service`(`servicekey`, `serviceconfig`, `interfacetype`, `entry`, `authcode`, `servicelevel`, `serviceflag`, `createtime`, `createuser`, `updatetime`, `updateuser`, `encryptflag`, `encryptprivatekey`, `encrypttype`) VALUES ( '" + path + "', '" + finalRiskAddress + "', 'rpc', "+entry+", '', 0, 1, now(), 0, NULL, NULL, 0, NULL, NULL);\r\n");
                            textAreaLog.appendText("\r\n");
                        });
                    }catch (Exception ex){
                        Platform.runLater(() -> {
                            textAreaLog.appendText("生成风控发生未知异常: " +printThrowable(ex));
                        });
                    }
                }
            });
        });
        Button btnTransferXlsx = new Button("写入xlsx");
        btnTransferXlsx.setPrefWidth(700);
        HBox hbBtnTransferXlsx = new HBox(100);
        hbBtnTransferXlsx.setAlignment(Pos.BOTTOM_CENTER);
        hbBtnTransferXlsx.setPrefWidth(700);
        hbBtnTransferXlsx.getChildren().add(btnTransferXlsx);
        grid.add(hbBtnTransferXlsx, 0, 5,4,1);
        componentMap.put("写入xlsx",btnTransferXlsx);

        btnTransferXlsx.setOnAction(e -> {
            Stage stage2=new Stage();
            stage2.setResizable(false);
            stage2.setOnCloseRequest(event -> stage2.close());
            Group root = new Group();
            Scene scene = new Scene(root, 220, 80);
            stage2.setScene(scene);
            stage2.setTitle("写入进度");
            final Label label = new Label();
            label.setText("进度:");
            ProgressBar  pb = new ProgressBar();
            ProgressIndicator pin = new ProgressIndicator();
            final HBox hb  = new HBox();
            hb.setSpacing(1);
            hb.setAlignment(Pos.CENTER);
            hb.getChildren().addAll(label, pb, pin);
            final VBox vb = new VBox();
            vb.setSpacing(1);
            vb.getChildren().add(hb);
            scene.setRoot(vb);
            stage2.show();
            pool.execute(()->{
                        try {
                            String id = targetIdField.getText();
                            String catId=null;
                            if(id.contains("cat_")){
                                catId=id.substring(4);
                            }
                            String[] ids=new String[]{id};
                            if(id.contains(",")) {
                                ids = id.split(",");
                            }
                            if(id.contains("，")){
                                ids=id.split("，");
                            }
                            if(catId!=null&&!"".equals(catId)){
                                JSONObject  jsonObject =YapiUtil.listCat(cookie,catId);
                                log.info("返回值"+jsonObject);
                                JSONObject data=jsonObject.getJSONObject("data");
                                JSONArray list= data.getJSONArray("list");
                                ids=new String[list.size()];
                                int i=0;
                                for(Object obj:list){
                                    JSONObject json= (JSONObject) obj;
                                    String _id=json.getString("_id");
                                    ids[i++]=_id;
                                }
                            }
                            log.info("要迁移的目标id "+Arrays.asList(ids));
                            for(String idT:ids) {
                                List<String> dataT = new ArrayList<>();
                                JSONObject apiInfo=YapiUtil.getApi(cookie,idT);
                                JSONObject data = apiInfo.getJSONObject("data");
                                String url = YapiUtil.getYapiUrl() + "/project/" + apiInfo.getString("project_id") + "/interface/api/" + data.getString("_id");
                                dataT.add(data.getString("title"));
                                dataT.add(url);
                                dataT.add(username);
                                dataT.add(VeDate.getFormatDate("yyyy/M/d"));
                                dataT.add("对接人");
                                dataT.add("是");
                                ExcelUtils.addList(dataT);
                            }
                            ExcelUtils.writeToExcel(pb,pin);
                            Platform.runLater(()->{
                                textAreaLog.appendText("日志写入xlsx成功!" + "\r\n");
                            });
                        }catch (Exception ex){
                            Platform.runLater(() -> {
                                textAreaLog.appendText("写入xlsx Yapi发生未知异常: "+printThrowable(ex));
                            });
                        }finally {
                            Platform.runLater(() -> {
                            pb.setProgress(-1);
                            pin.setProgress(-1);
                            stage2.close();
                            });
                        }
                    });
                }
        );
        textAreaLog.setPrefColumnCount(5);
        textAreaLog.setEditable(true);
        textAreaLog.setWrapText(true);
        grid.add(textAreaLog, 0, 6,4,4);
        if(plugIntf!=null){
            plugIntf.buildTransferComponent(grid,10,componentMap);
        }
        ScrollPane scrollPane=new ScrollPane();
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setContent(grid);
        return scrollPane;
    }

    private ScrollPane createAddedWindow(String username,String cookie){
        Map<String, Object> componentMap=new ConcurrentHashMap<>();
        GridPane grid = new GridPane();
        grid.setMinSize(100,100);
        grid.setAlignment(Pos.TOP_LEFT);
        grid.setHgap(5);
        grid.setVgap(5);
        grid.setPadding(new Insets(10, 10, 10, 10));

        JSONObject  groupJson=YapiUtil.listGroup(cookie);
        JSONArray jsonArray=groupJson.getJSONArray("data");
        Map<String,String> groupMap=new HashMap<>();
        for(Object obj:jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            String group_name = jsonObject.getString("group_name");
            String _id=jsonObject.getString("_id");
            groupMap.put(group_name,_id);
        }

        Map<String,TextField> textFieldMap=new HashMap<>();
        Label groupName = new Label("groupName:");
        groupName.setPrefWidth(123);
        grid.add(groupName, 0, 0);

        ComboBox<Map.Entry<String,String>> targetgroupNameCbT = new ComboBox(FXCollections.observableArrayList(groupMap.entrySet()));
        targetgroupNameCbT.setPrefWidth(600);
        grid.add(targetgroupNameCbT, 1, 0,3,1);
        //数据转换
        targetgroupNameCbT.setConverter(new StringConverter<Map.Entry<String,String>>() {
            //只显示名字
            @Override
            public String toString(Map.Entry<String,String> entry) {
                String value = entry.getKey();
                return value;
            }

            @Override
            public Map.Entry<String,String>  fromString(String string) {
                String value=groupMap.get(string);
                return new Map.Entry<String, String>() {
                    @Override
                    public String getKey() {
                        return string;
                    }

                    @Override
                    public String getValue() {
                        return value;
                    }

                    @Override
                    public String setValue(String value) {
                        return value;
                    }
                };
            }
        });
        Label project = new Label("project:");
        project.setPrefWidth(123);
        grid.add(project, 0, 1);

        ComboBox targetProjectCbT = new ComboBox();
        targetProjectCbT.setPrefWidth(600);
        grid.add(targetProjectCbT, 1, 1,3,1);

        Map<String,String> projectMapT=new HashMap<>();
        targetgroupNameCbT.setOnAction(e->{
            pool.execute(()->{
                projectMapT.clear();
                JSONObject  projectJson=YapiUtil.listProject(cookie,targetgroupNameCbT.getValue().getValue());
                JSONArray jsonArray1=projectJson.getJSONObject("data").getJSONArray("list");
                for(Object obj1:jsonArray1) {
                    JSONObject jsonObject = (JSONObject) obj1;
                    String name = jsonObject.getString("name");
                    String project_id=jsonObject.getString("_id");
                    projectMapT.put(name,project_id);
                }
                Platform.runLater(() -> {
                    targetProjectCbT.setItems(FXCollections.observableArrayList(projectMapT.keySet().toArray()));
                    targetProjectCbT.getSelectionModel().select(0);
                });
            });
        });

        Label menu = new Label("menu:");
        menu.setPrefWidth(123);
        grid.add(menu, 0, 2);

        ComboBox targetMenuCbT = new ComboBox();
        targetMenuCbT.setPrefWidth(600);
        grid.add(targetMenuCbT, 1, 2,3,1);

        Map<String,String> menuMapT=new HashMap<>();
        targetProjectCbT.setOnAction(e->{
            pool.execute(()->{
                menuMapT.clear();
                if(targetProjectCbT.getValue()!=null) {
                    String projectId = targetProjectCbT.getValue().toString();
                    JSONObject projectJson = YapiUtil.listMenu(cookie, projectMapT.get(projectId));
                    JSONArray jsonArray2 = projectJson.getJSONArray("data");
                    for (Object obj2 : jsonArray2) {
                        JSONObject jsonObject = (JSONObject) obj2;
                        String name = jsonObject.getString("name");
                        String catid = jsonObject.getString("_id");
                        menuMapT.put(name, catid);
                    }
                    Platform.runLater(() -> {
                        targetMenuCbT.setItems(FXCollections.observableArrayList(menuMapT.keySet().toArray()));
                        targetMenuCbT.getSelectionModel().select(0);
                    });
                }
            });
        });

        Label title = new Label("接口名称(必填):");
        title.setPrefWidth(123);
        grid.add(title, 0, 3);
        TextField titleField = new TextField();
        titleField.setPrefWidth(308);
        grid.add(titleField, 1, 3,3,1);
        textFieldMap.put("titleField",titleField);

        Label path = new Label("接口路径(必填):");
        path.setPrefWidth(123);
        grid.add(path, 0, 4);

        TextField pathField = new TextField();
        pathField.setPrefWidth(308);
        grid.add(pathField, 1, 4,3,1);
        textFieldMap.put("pathField",pathField);

        Label reqParam = new Label("请求数据(json格式):");
        reqParam.setPrefWidth(123);
        grid.add(reqParam, 0, 5);
        TextField reqParamField = new TextField();
        reqParamField.setPrefWidth(308);
        grid.add(reqParamField, 1, 5,3,1);
        textFieldMap.put("reqParamField",reqParamField);

        Label resBody = new Label("返回数据(json格式):");
        resBody.setPrefWidth(123);
        grid.add(resBody, 0, 6);
        TextField resBodyField = new TextField();
        resBodyField.setPrefWidth(308);
        grid.add(resBodyField, 1, 6,3,1);
        textFieldMap.put("resBodyField",resBodyField);


        Label rpcAddress = new Label("rpc地址路径:");
        rpcAddress.setPrefWidth(123);
        grid.add(rpcAddress, 0, 7);
        TextField rpcAddressField = new TextField();
        rpcAddressField.setPrefWidth(308);
        grid.add(rpcAddressField, 1, 7,3,1);
        textFieldMap.put("rpcAddressField",rpcAddressField);


        TextArea textAreaLog=new TextArea();
        textAreaLog.setPrefColumnCount(5);
        textAreaLog.setEditable(true);
        textAreaLog.setWrapText(true);
        grid.add(textAreaLog, 0, 8,4,4);


        Button btnQuery = new Button("添加Query参数");
        HBox hbBtnQuery = new HBox(10);
        hbBtnQuery.setAlignment(Pos.BOTTOM_LEFT);
        hbBtnQuery.getChildren().add(btnQuery);
        grid.add(hbBtnQuery, 0, 12,1,1);

        List<Map<String,TextField>> reQueryList=new ArrayList<>();
        final AtomicInteger index=new AtomicInteger(15);
        Button btnDel = new Button("删除Query参数");
        HBox hbBtnDel = new HBox(10);
        btnDel.setAlignment(Pos.BOTTOM_CENTER);
        hbBtnDel.getChildren().add(btnDel);
        grid.add(hbBtnDel, 2, 12,3,1);

        btnDel.setOnAction(k -> {
            int tempIndex= index.get()-15;
            if(tempIndex==0){
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("yapi返回");
                alert.setHeaderText(null);
                alert.setContentText("我是有底线的!!!");
                alert.showAndWait();
                return;
            }
            index.decrementAndGet();
            Map<String,TextField> tempMap=reQueryList.get(tempIndex);
            for(TextField textField: tempMap.values()){
                grid.getChildren().remove(textField);
            }
            reQueryList.remove(tempMap);
        });


        HBox hbBtn=createAddButton(index,grid,username,cookie,textAreaLog,targetgroupNameCbT,targetProjectCbT,targetMenuCbT,groupMap,projectMapT,menuMapT,textFieldMap,reQueryList);
        grid.add(hbBtn, 3, 12,1,1);


        btnQuery.setOnAction(e -> {

            Map<String,TextField> reQuery=new HashMap<>();
            TextField nameFieldTemp = new TextField();
            nameFieldTemp.setPrefWidth(185);
            grid.add(nameFieldTemp, 0, index.get(),1,1);
            reQuery.put("name",nameFieldTemp);

            TextField exampleFieldTemp = new TextField();
            exampleFieldTemp.setPrefWidth(185);
            grid.add(exampleFieldTemp, 1, index.get(),1,1);
            reQuery.put("example",exampleFieldTemp);

            TextField descFieldTemp = new TextField();
            descFieldTemp.setPrefWidth(185);
            grid.add(descFieldTemp, 2, index.get(),2,1);
            reQuery.put("desc",descFieldTemp);

            index.incrementAndGet();
            reQueryList.add(reQuery);

        });

        Label name = new Label("name");
        name.setPrefWidth(185);
        grid.add(name, 0, 13);
        Label example = new Label("example");
        example.setPrefWidth(185);
        grid.add(example, 1, 13);
        Label desc = new Label("desc:");
        desc.setPrefWidth(185);
        grid.add(desc, 2, 13);

        Map<String,TextField> reQueryt=new HashMap<>();
        TextField nameField = new TextField();
        nameField.setPrefWidth(185);
        grid.add(nameField, 0, 14);
        reQueryt.put("name",nameField);

        TextField exampleField = new TextField();
        exampleField.setPrefWidth(185);
        grid.add(exampleField, 1, 14);
        reQueryt.put("example",exampleField);

        TextField descField = new TextField();
        descField.setPrefWidth(185);
        grid.add(descField, 2, 14,2,1);
        reQueryt.put("desc",descField);
        reQueryList.add(reQueryt);
        ScrollPane scrollPane=new ScrollPane();
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setContent(grid);
        return scrollPane;
    }
//    private Scene createMainScene(String username,String cookie){
//        GridPane grid = new GridPane();
//        grid.setMinSize(100,100);
//        grid.setAlignment(Pos.TOP_LEFT);
//        grid.setHgap(5);
//        grid.setVgap(5);
//        grid.setPadding(new Insets(10, 10, 10, 10));
//
//        Text scenetitleTemp = new Text("Yapi迁移参数设置");
//        scenetitleTemp.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
//        grid.add(scenetitleTemp, 0, 0, 3, 1);
//
//        Label targetId = new Label("Ids(,分割)||catId");
//        targetId.setPrefWidth(100);
//        grid.add(targetId, 0, 1);
//
//        Label targetgroupName = new Label("groupName");
//        targetgroupName.setPrefWidth(100);
//        grid.add(targetgroupName, 1, 1);
//
//        Label targetproject = new Label("project:");
//        targetproject.setPrefWidth(100);
//        grid.add(targetproject, 2, 1);
//
//        Label targetmenu = new Label("menu:");
//        targetmenu.setPrefWidth(100);
//        grid.add(targetmenu, 3, 1);
//
//        TextField targetIdField = new TextField();
//        targetIdField.setPrefWidth(100);
//        grid.add(targetIdField, 0, 2,1,1);
//
//        TextArea textAreaLog=new TextArea();
//        JSONObject  groupJson=YapiUtil.listGroup(cookie);
//        JSONArray jsonArray=groupJson.getJSONArray("data");
//        Map<String,String> groupMap=new HashMap<>();
//        for(Object obj:jsonArray) {
//            JSONObject jsonObject = (JSONObject) obj;
//            String group_name = jsonObject.getString("group_name");
//            String _id=jsonObject.getString("_id");
//            groupMap.put(group_name,_id);
//        }
//        ComboBox<Map.Entry<String,String>> targetgroupNameCb = new ComboBox(FXCollections.observableArrayList(groupMap.entrySet()));
//        targetgroupNameCb.autosize();
//        targetgroupNameCb.setPrefWidth(154);
//        //数据转换
//        targetgroupNameCb.setConverter(new StringConverter<Map.Entry<String,String>>() {
//            //只显示名字
//            @Override
//            public String toString(Map.Entry<String,String> entry) {
//                String value=null;
//                if(entry!=null) {
//                     value = entry.getKey();
//                }
//                return value;
//            }
//
//            @Override
//            public Map.Entry<String,String>  fromString(String string) {
//                String value=groupMap.get(string);
//                return new Map.Entry<String, String>() {
//                    @Override
//                    public String getKey() {
//                        return string;
//                    }
//
//                    @Override
//                    public String getValue() {
//                        return value;
//                    }
//
//                    @Override
//                    public String setValue(String value) {
//                        return value;
//                    }
//                };
//            }
//        });
//        grid.add(targetgroupNameCb, 1, 2,1,1);
//
//        ComboBox targetProjectCb = new ComboBox();
//        targetProjectCb.setPrefWidth(154);
//        targetProjectCb.autosize();
//        grid.add(targetProjectCb, 2, 2,1,1);
//
//        ComboBox targetMenuCb = new ComboBox();
//        targetMenuCb.setPrefWidth(154);
//        targetMenuCb.autosize();
//        grid.add(targetMenuCb, 3, 2,1,1);
//
//        Map<String,String> projectMap=new HashMap<>();
//        targetgroupNameCb.setOnAction(e->{
//            pool.execute(()->{
//                projectMap.clear();
//                JSONObject  projectJson=YapiUtil.listProject(cookie,targetgroupNameCb.getValue().getValue());
//                JSONArray jsonArray1=projectJson.getJSONObject("data").getJSONArray("list");
//                for(Object obj1:jsonArray1) {
//                    JSONObject jsonObject = (JSONObject) obj1;
//                    String name = jsonObject.getString("name");
//                    String project_id=jsonObject.getString("_id");
//                    projectMap.put(name,project_id);
//                }
//                Platform.runLater(()->{
//                        targetProjectCb.setItems(FXCollections.observableArrayList(projectMap.keySet().toArray()));
//                        targetProjectCb.getSelectionModel().select(0);
//                });
//            });
//        });
//
//        Map<String,String> menuMap=new HashMap<>();
//        targetProjectCb.setOnAction(e->{
//            pool.execute(()-> {
//                menuMap.clear();
//                if (targetProjectCb.getValue() != null) {
//                    String projectId = targetProjectCb.getValue().toString();
//                    JSONObject menuJson = YapiUtil.listMenu(cookie, projectMap.get(projectId));
//                    JSONArray jsonArray2 = menuJson.getJSONArray("data");
//                    for (Object obj2 : jsonArray2) {
//                        JSONObject jsonObject = (JSONObject) obj2;
//                        String name = jsonObject.getString("name");
//                        String catid = jsonObject.getString("_id");
//                        menuMap.put(name, catid);
//                    }
//                    Platform.runLater(() -> {
//                        targetMenuCb.setItems(FXCollections.observableArrayList(menuMap.keySet().toArray()));
//                        targetMenuCb.getSelectionModel().select(0);
//                    });
//                }
//            });
//        });
//
//        Label pathLabel = new Label("最新路径(单个有效):");
//        pathLabel.setPrefWidth(110);
//        grid.add(pathLabel, 0, 3);
//        TextField newPathField = new TextField();
//        newPathField.setPrefWidth(208);
//        grid.add(newPathField, 1, 3,2,1);
//        CheckBox isAddNew = new CheckBox();
//        isAddNew.setText("是否自动批量更新path");
//        isAddNew.setSelected(false);
//        grid.add(isAddNew, 3, 3,1,1);
//
//        Button btnTransfer = new Button("迁移");
//        btnTransfer.setPrefWidth(750);
//        HBox hbBtnTransfer = new HBox(100);
//        hbBtnTransfer.setAlignment(Pos.BOTTOM_CENTER);
//        hbBtnTransfer.setPrefWidth(750);
//        hbBtnTransfer.getChildren().add(btnTransfer);
//        grid.add(hbBtnTransfer, 0, 4,4,1);
//        btnTransfer.setOnAction(e -> {
//            pool.execute(()->{
//                try {
//                    String id = targetIdField.getText();
//                    String catId=null;
//                    if(id.contains("cat_")){
//                        catId=id.substring(4);
//                    }
//                    String project = projectMap.get(targetProjectCb.getValue().toString());
//                    String menu = menuMap.get(targetMenuCb.getValue().toString());
//                    String newPath=newPathField.getText();
//                    String[] ids=new String[]{id};
//                    if(id.contains(",")) {
//                        ids = id.split(",");
//                    }
//                    if(id.contains("，")){
//                        ids=id.split("，");
//                    }
//                    if(catId!=null&&!"".equals(catId)){
//                        JSONObject  jsonObject =YapiUtil.listCat(cookie,catId);
//                        log.info("返回值"+jsonObject);
//                        JSONObject data=jsonObject.getJSONObject("data");
//                        JSONArray list= data.getJSONArray("list");
//                        ids=new String[list.size()];
//                        int i=0;
//                        for(Object obj:list){
//                            JSONObject json= (JSONObject) obj;
//                            String _id=json.getString("_id");
//                            ids[i++]=_id;
//                        }
//                    }
//                    log.info("要迁移的目标id "+Arrays.asList(ids));
//                    newPath=ids.length==1?newPath:null;
//                    for(String idTemp:ids){
//                        List<String> dataT = new ArrayList<>();
//                        JSONObject tempApiInfo = YapiUtil.transferYapi(cookie, project, menu, idTemp, isAddNew.isSelected(),newPath,properties);
//                        try {
//                            /*int errcode = tempApiInfo.getInteger("errcode");
//                            if (errcode == 40022) {
//                                tempApiInfo = YapiUtil.transferYapi(cookie, project, menu, idTemp, true);
//                            }*/
//                            log.info(tempApiInfo.toJSONString());
//                            JSONObject apiInfo = tempApiInfo;
//                            int errcodeFinal = apiInfo.getInteger("errcode");
//                           JSONArray jsonArray1= apiInfo.getJSONArray("data");
//                           if(jsonArray1.size()>0) {
//                               JSONObject data = apiInfo.getJSONArray("data").getJSONObject(0);
//                               String url = YapiUtil.getYapiUrl() + "/project/" + project + "/interface/api/" + data.getString("_id");
//                               dataT.add("新增");
//                               dataT.add(data.getString("title"));
//                               dataT.add(url);
//                               dataT.add(username);
//                               dataT.add(VeDate.getFormatDate("yyyy/M/d"));
//                               dataT.add("");
//                               dataT.add("新需求");
//                               dataT.add(username);
//                               ExcelUtils.addList(dataT);
//                           }
//                            Platform.runLater(() -> {
//                                textAreaLog.appendText("迁移Yapi结果: " + ((errcodeFinal == 0) ? "成功" : "失败") + "    id:" + idTemp + " ---> group:" + targetgroupNameCb.getValue().getKey() + ", project:" + targetProjectCb.getValue().toString() + ", menu:" + targetMenuCb.getValue().toString() + "  result:" + apiInfo.toJSONString() + "\r\n");
//                            });
//                        }catch (Exception ex){
//                            ex.printStackTrace();
//                            JSONObject finalTempApiInfo = tempApiInfo;
//                            Platform.runLater(() -> {
//                                textAreaLog.appendText("迁移Yapi发生未知异常: " + finalTempApiInfo.toJSONString()+"\r\n"+printThrowable(ex));
//                            });
//                        }
//                        }
//                }catch (Exception ex){
//                    ex.printStackTrace();
//                    Platform.runLater(() -> {
//                    textAreaLog.appendText("迁移Yapi发生未知异常: " +printThrowable(ex));
//                    });
//                }
//            });
//        });
//
//        Button riskManage = new Button("生成风控");
//        riskManage.setPrefWidth(750);
//        HBox hbBtnRiskManage = new HBox(100);
//        hbBtnRiskManage.setAlignment(Pos.BOTTOM_CENTER);
//        hbBtnRiskManage.setPrefWidth(750);
//        hbBtnRiskManage.getChildren().add(riskManage);
//        grid.add(hbBtnRiskManage, 0, 5,3,1);
//
//        CheckBox isEntry = new CheckBox();
//        isEntry.setText("是否entry接口");
//        isEntry.setSelected(true);
//        grid.add(isEntry, 3, 5,1,1);
//
//        riskManage.setOnAction(action->{
//            pool.execute(()->{
//                String id = targetIdField.getText();
//                int entry=isEntry.isSelected()?0:1;
//                List<String> idList=new ArrayList<>();
//                if(id==null||"".equals(id)){
//                    String menu = menuMap.get(targetMenuCb.getValue().toString());
//                    JSONObject  jsonObject =YapiUtil.listCat(cookie,menu);
//                    log.info("返回值"+jsonObject);
//                    JSONObject data=jsonObject.getJSONObject("data");
//                    JSONArray list= data.getJSONArray("list");
//                    for(Object obj:list){
//                        JSONObject json= (JSONObject) obj;
//                        String _id=json.getString("_id");
//                        idList.add(_id);
//                    }
//                }else{
//                    idList.addAll(Arrays.asList(id.split(",")));
//                }
//                Platform.runLater(() -> {
//                textAreaLog.appendText("风控SQL:\r\n");
//                });
//                for(String idTemp:idList){
//                    try {
//                        JSONObject jsonObject = YapiUtil.getApi(cookie, idTemp);
//                        JSONObject data = jsonObject.getJSONObject("data");
//                        String path = data.getString("path").split("/")[1];
//                        String riskAddress = "未知风控路径";
//                        String markdown = data.getString("markdown");
//                        String[] risks = markdown.split("[\\s\\n]");
//                        for (String temp : risks) {
//                            String risk = temp.trim();
//                            if (risk.contains("-") && risk.startsWith("com.zl.")) {
//                                riskAddress = risk;
//                                break;
//                            }
//                        }
//                        String finalRiskAddress=riskAddress;
//                        Platform.runLater(() -> {
//                            textAreaLog.appendText("delete from pub_gateway_service where servicekey='" + path + "';\r\n");
//                            textAreaLog.appendText("INSERT INTO `pub_gateway_service`(`servicekey`, `serviceconfig`, `interfacetype`, `entry`, `authcode`, `servicelevel`, `serviceflag`, `createtime`, `createuser`, `updatetime`, `updateuser`, `encryptflag`, `encryptprivatekey`, `encrypttype`) VALUES ( '" + path + "', '" + finalRiskAddress + "', 'rpc', "+entry+", '', 0, 1, now(), 0, NULL, NULL, 0, NULL, NULL);\r\n");
//                            textAreaLog.appendText("\r\n");
//                        });
//                    }catch (Exception ex){
//                        Platform.runLater(() -> {
//                            textAreaLog.appendText("生成风控发生未知异常: " +printThrowable(ex));
//                        });
//                    }
//                }
//            });
//        });
//
//
//        Button btnTransferXlsx = new Button("写入xlsx");
//        btnTransferXlsx.setPrefWidth(750);
//        HBox hbBtnTransferXlsx = new HBox(100);
//        hbBtnTransferXlsx.setAlignment(Pos.BOTTOM_CENTER);
//        hbBtnTransferXlsx.setPrefWidth(750);
//        hbBtnTransferXlsx.getChildren().add(btnTransferXlsx);
//        grid.add(hbBtnTransferXlsx, 0, 6,4,1);
//        btnTransferXlsx.setOnAction(e -> {
//                pool.execute(()->{
//                    try {
//                        ExcelUtils.writeToExcel();
//                        Platform.runLater(() -> { textAreaLog.appendText("日志写入xlsx成功!" + "\r\n");
//                        });
//                    }catch (Exception ex){
//                        Platform.runLater(() -> {
//                            textAreaLog.appendText("写入xlsx Yapi发生未知异常: "+printThrowable(ex));
//                        });
//                    }
//                });
//                }
//                );
//
//        textAreaLog.setPrefColumnCount(5);
//        textAreaLog.setEditable(true);
//        grid.add(textAreaLog, 0, 7,4,4);
//
//        Text scenetitle = new Text("Yapi新增参数设置");
//        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
//        grid.add(scenetitle, 0, 11, 5, 1);
//
//        Map<String,TextField> textFieldMap=new HashMap<>();
//        Label groupName = new Label("groupName:");
//        groupName.setPrefWidth(123);
//        grid.add(groupName, 0, 12);
//
//        ComboBox<Map.Entry<String,String>> targetgroupNameCbT = new ComboBox(FXCollections.observableArrayList(groupMap.entrySet()));
//        targetgroupNameCbT.setPrefWidth(600);
//        grid.add(targetgroupNameCbT, 1, 12,3,1);
//        //数据转换
//        targetgroupNameCbT.setConverter(new StringConverter<Map.Entry<String,String>>() {
//            //只显示名字
//            @Override
//            public String toString(Map.Entry<String,String> entry) {
//                String value = entry.getKey();
//                return value;
//            }
//
//            @Override
//            public Map.Entry<String,String>  fromString(String string) {
//                String value=groupMap.get(string);
//                return new Map.Entry<String, String>() {
//                    @Override
//                    public String getKey() {
//                        return string;
//                    }
//
//                    @Override
//                    public String getValue() {
//                        return value;
//                    }
//
//                    @Override
//                    public String setValue(String value) {
//                        return value;
//                    }
//                };
//            }
//        });
//        Label project = new Label("project:");
//        project.setPrefWidth(123);
//        grid.add(project, 0, 13);
//
//        ComboBox targetProjectCbT = new ComboBox();
//        targetProjectCbT.setPrefWidth(600);
//        grid.add(targetProjectCbT, 1, 13,3,1);
//
//        Map<String,String> projectMapT=new HashMap<>();
//        targetgroupNameCbT.setOnAction(e->{
//            pool.execute(()->{
//                projectMapT.clear();
//                JSONObject  projectJson=YapiUtil.listProject(cookie,targetgroupNameCbT.getValue().getValue());
//                JSONArray jsonArray1=projectJson.getJSONObject("data").getJSONArray("list");
//                for(Object obj1:jsonArray1) {
//                    JSONObject jsonObject = (JSONObject) obj1;
//                    String name = jsonObject.getString("name");
//                    String project_id=jsonObject.getString("_id");
//                    projectMapT.put(name,project_id);
//                }
//                Platform.runLater(() -> {
//                    targetProjectCbT.setItems(FXCollections.observableArrayList(projectMapT.keySet().toArray()));
//                    targetProjectCbT.getSelectionModel().select(0);
//                });
//            });
//        });
//
//        Label menu = new Label("menu:");
//        menu.setPrefWidth(123);
//        grid.add(menu, 0, 14);
//
//        ComboBox targetMenuCbT = new ComboBox();
//        targetMenuCbT.setPrefWidth(600);
//        grid.add(targetMenuCbT, 1, 14,3,1);
//
//        Map<String,String> menuMapT=new HashMap<>();
//        targetProjectCbT.setOnAction(e->{
//            pool.execute(()->{
//                menuMapT.clear();
//                if(targetProjectCbT.getValue()!=null) {
//                    String projectId = targetProjectCbT.getValue().toString();
//                    JSONObject projectJson = YapiUtil.listMenu(cookie, projectMapT.get(projectId));
//                    JSONArray jsonArray2 = projectJson.getJSONArray("data");
//                    for (Object obj2 : jsonArray2) {
//                        JSONObject jsonObject = (JSONObject) obj2;
//                        String name = jsonObject.getString("name");
//                        String catid = jsonObject.getString("_id");
//                        menuMapT.put(name, catid);
//                    }
//                    Platform.runLater(() -> {
//                        targetMenuCbT.setItems(FXCollections.observableArrayList(menuMapT.keySet().toArray()));
//                        targetMenuCbT.getSelectionModel().select(0);
//                    });
//                }
//            });
//        });
//
//        Label title = new Label("接口名称(必填):");
//        title.setPrefWidth(123);
//        grid.add(title, 0, 15);
//        TextField titleField = new TextField();
//        titleField.setPrefWidth(308);
//        grid.add(titleField, 1, 15,3,1);
//        textFieldMap.put("titleField",titleField);
//
//        Label path = new Label("接口路径(必填):");
//        path.setPrefWidth(123);
//        grid.add(path, 0, 16);
//
//        TextField pathField = new TextField();
//        pathField.setPrefWidth(308);
//        grid.add(pathField, 1, 16,3,1);
//        textFieldMap.put("pathField",pathField);
//
//        Label reqParam = new Label("请求数据(json格式):");
//        reqParam.setPrefWidth(123);
//        grid.add(reqParam, 0, 17);
//        TextField reqParamField = new TextField();
//        reqParamField.setPrefWidth(308);
//        grid.add(reqParamField, 1, 17,3,1);
//        textFieldMap.put("reqParamField",reqParamField);
//
//        Label resBody = new Label("返回数据(json格式):");
//        resBody.setPrefWidth(123);
//        grid.add(resBody, 0, 18);
//        TextField resBodyField = new TextField();
//        resBodyField.setPrefWidth(308);
//        grid.add(resBodyField, 1, 18,3,1);
//        textFieldMap.put("resBodyField",resBodyField);
//
//
//        Label rpcAddress = new Label("rpc地址路径:");
//        rpcAddress.setPrefWidth(123);
//        grid.add(rpcAddress, 0, 19);
//        TextField rpcAddressField = new TextField();
//        rpcAddressField.setPrefWidth(308);
//        grid.add(rpcAddressField, 1, 19,3,1);
//        textFieldMap.put("rpcAddressField",rpcAddressField);
//
//        Button btnQuery = new Button("添加Query参数");
//        HBox hbBtnQuery = new HBox(10);
//        hbBtnQuery.setAlignment(Pos.BOTTOM_LEFT);
//        hbBtnQuery.getChildren().add(btnQuery);
//        grid.add(hbBtnQuery, 0, 20,1,1);
//
//        List<Map<String,TextField>> reQueryList=new ArrayList<>();
//        final AtomicInteger index=new AtomicInteger(23);
//        Button btnDel = new Button("删除Query参数");
//        HBox hbBtnDel = new HBox(10);
//        btnDel.setAlignment(Pos.BOTTOM_CENTER);
//        hbBtnDel.getChildren().add(btnDel);
//        grid.add(hbBtnDel, 2, 20,3,1);
//
//        btnDel.setOnAction(k -> {
//            int tempIndex= index.get()-23;
//            if(tempIndex==0){
//                Alert alert = new Alert(Alert.AlertType.INFORMATION);
//                alert.setTitle("yapi返回");
//                alert.setHeaderText(null);
//                alert.setContentText("我是有底线的!!!");
//                alert.showAndWait();
//                return;
//            }
//            index.decrementAndGet();
//            Map<String,TextField> tempMap=reQueryList.get(tempIndex);
//            for(TextField textField: tempMap.values()){
//                grid.getChildren().remove(textField);
//            }
//            reQueryList.remove(tempMap);
//        });
//
//
//        HBox hbBtn=createAddButton(index,grid,username,cookie,textAreaLog,targetgroupNameCbT,targetProjectCbT,targetMenuCbT,groupMap,projectMapT,menuMapT,textFieldMap,reQueryList);
//        grid.add(hbBtn, 3, 20,1,1);
//
//
//        btnQuery.setOnAction(e -> {
//
//            Map<String,TextField> reQuery=new HashMap<>();
//            TextField nameFieldTemp = new TextField();
//            nameFieldTemp.setPrefWidth(185);
//            grid.add(nameFieldTemp, 0, index.get(),1,1);
//            reQuery.put("name",nameFieldTemp);
//
//            TextField exampleFieldTemp = new TextField();
//            exampleFieldTemp.setPrefWidth(185);
//            grid.add(exampleFieldTemp, 1, index.get(),1,1);
//            reQuery.put("example",exampleFieldTemp);
//
//            TextField descFieldTemp = new TextField();
//            descFieldTemp.setPrefWidth(185);
//            grid.add(descFieldTemp, 2, index.get(),2,1);
//            reQuery.put("desc",descFieldTemp);
//
//            index.incrementAndGet();
//            reQueryList.add(reQuery);
//
//        });
//
//        Label name = new Label("name");
//        name.setPrefWidth(185);
//        grid.add(name, 0, 21);
//        Label example = new Label("example");
//        example.setPrefWidth(185);
//        grid.add(example, 1, 22);
//        Label desc = new Label("desc:");
//        desc.setPrefWidth(185);
//        grid.add(desc, 2, 21);
//
//        Map<String,TextField> reQueryt=new HashMap<>();
//        TextField nameField = new TextField();
//        nameField.setPrefWidth(185);
//        grid.add(nameField, 0, 22);
//        reQueryt.put("name",nameField);
//
//        TextField exampleField = new TextField();
//        exampleField.setPrefWidth(185);
//        grid.add(exampleField, 1, 22);
//        reQueryt.put("example",exampleField);
//
//        TextField descField = new TextField();
//        descField.setPrefWidth(185);
//        grid.add(descField, 2, 22,2,1);
//        reQueryt.put("desc",descField);
//        reQueryList.add(reQueryt);
//
//        ScrollPane scrollPane=new ScrollPane();
//        //scrollPane.setPrefViewportWidth(1000);
//        //scrollPane.fitToWidthProperty();
//        //scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
//        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
//        scrollPane.setContent(grid);
//        Scene scene = new Scene(scrollPane, 750, 800);
//        return scene;
//    }

    private static Properties getProperties(String pathname)
    {
        Properties p =System.getProperties() ;
        try {
            p.load(new FileInputStream(new File(pathname)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return p;
    }
    private HBox createAddButton(AtomicInteger index,GridPane grid ,String username,String cookie,TextArea textAreaLog,ComboBox<Map.Entry<String,String>> targetgroupNameCbT,ComboBox targetProjectCbT, ComboBox targetMenuCbT,Map<String,String> groupMapT ,Map<String,String> projectMapT,Map<String,String> menuMapT,Map<String,TextField> textFieldMap,List<Map<String,TextField>> reQueryList){
        Button btn = new Button("添加Yapi");
        HBox hbBtn = new HBox(10);
        hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtn.getChildren().add(btn);
        btn.setOnAction(e -> {
            try {
                Map<String,String> keyValueMap=Form.getKeyValueMap();
                String projectValue = projectMapT.get(targetProjectCbT.getValue());
                String menuValue = menuMapT.get(targetMenuCbT.getValue());
                String pathValue = textFieldMap.get("pathField").getText();
                String titleValue = textFieldMap.get("titleField").getText();
                String reqParamValue = textFieldMap.get("reqParamField").getText();
                String rpcAddressValue=textFieldMap.get("rpcAddressField").getText();
                List<Map<String, Object>> queryMapList = new ArrayList<>();
                if (reqParamValue != null && !"".equals(reqParamValue)) {
                    JSONObject jsonObjectReq = JSONObject.parseObject(reqParamValue);
                    for (Map.Entry<String, Object> entry : jsonObjectReq.entrySet()) {
                        String key = entry.getKey();
                        if (blackList.contains(key)) {
                            continue;
                        }
                        Object value = entry.getValue();
                        Map p = new HashMap();
                        p.put("required", "0");
                        p.put("name", key);
                        p.put("example", value);
                        p.put("desc", keyValueMap.get(key)==null?"":keyValueMap.get(key));
                        queryMapList.add(p);
                    }
                }
                String resBodyValue = textFieldMap.get("resBodyField").getText();
                for (Map<String, TextField> map : reQueryList) {
                    Map<String, Object> temp = new HashMap<>();
                    for (Map.Entry<String, TextField> entry : map.entrySet()) {
                        temp.put(entry.getKey(), entry.getValue().getText());
                    }
                    if (temp.get("name") != null && !temp.get("name").equals("")) {
                        temp.put("required", "0");
                        temp.put("desc", keyValueMap.get(temp.get("name"))==null?"":keyValueMap.get(temp.get("name")));
                        queryMapList.add(temp);
                    }
                }
                String  markdown=(rpcAddressValue==null||"".equals(rpcAddressValue))?"":"rpc路径地址: "+rpcAddressValue;
                JSONObject result = YapiUtil.addYapi(username, cookie, projectValue, menuValue, pathValue, titleValue, resBodyValue, queryMapList,markdown);
                int errcode = result.getInteger("errcode");
                String errmsg = result.getString("errmsg");
                textAreaLog.appendText("新增Yapi结果: "+((errcode==0)?"成功":"失败")+"   group:" +targetgroupNameCbT.getValue().getKey() +" project:" +targetProjectCbT.getValue()+" menu:"+targetMenuCbT.getValue()+" titleValue:"+titleValue+" path:"+pathValue+" result:" +result.toJSONString()+"\r\n");
                if(errcode==0){
                    JSONObject data=result.getJSONObject("data");
                    String url=YapiUtil.getYapiUrl()+"/project/"+data.getString("project_id")+"/interface/api/"+data.getString("_id");
                    textAreaLog.appendText("yapi路径地址: "+url+"\r\n");
                    if(rpcAddressValue!=null&&!"".equals(rpcAddressValue)) {
                        textAreaLog.appendText("风控SQL:\r\n");
                        textAreaLog.appendText("delete from pub_gateway_service where servicekey='" + pathValue + "';\r\n");
                        textAreaLog.appendText("INSERT INTO `pub_gateway_service`(`servicekey`, `serviceconfig`, `interfacetype`, `entry`, `authcode`, `servicelevel`, `serviceflag`, `createtime`, `createuser`, `updatetime`, `updateuser`, `encryptflag`, `encryptprivatekey`, `encrypttype`) VALUES ( '" + pathValue + "', '" + rpcAddressValue + "', 'rpc', '0', '', 0, 1, now(), 0, NULL, NULL, 0, NULL, NULL);\r\n");
                    }
                }
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("yapi返回");
                alert.setHeaderText(null);
                alert.setContentText(errmsg);
                alert.showAndWait();
                if (errcode == 0) {
                    textFieldMap.get("pathField").clear();
                    textFieldMap.get("titleField").clear();
                    textFieldMap.get("reqParamField").clear();
                    textFieldMap.get("resBodyField").clear();
                    textFieldMap.get("rpcAddressField").clear();
                    if (reQueryList.size() > 1) {
                        for (int i = 1; i < reQueryList.size(); i++) {
                            Map<String, TextField> temp = reQueryList.get(i);
                            for (Map.Entry<String, TextField> entry : temp.entrySet()) {
                                grid.getChildren().remove(entry.getValue());
                            }
                        }
                    }
                    Map<String, TextField> index1Map = reQueryList.get(0);
                    reQueryList.clear();
                    reQueryList.add(index1Map);
                    index.set(19);
                }
            }catch (Exception ex){
                textAreaLog.appendText("新增Yapi发生未知异常: " +printThrowable(ex));
            }
        });
        return hbBtn;
    }
    public static void writeFileString(String fileName, String str){
        try {
            File writeName = new File(fileName);
            writeName.createNewFile();
            try (FileWriter writer = new FileWriter(writeName, false);
                 BufferedWriter out = new BufferedWriter(writer)){
                out.write(str);
                out.newLine();   // 换行
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeFileMap(String fileName, Map<String,String> data){

        try {
            File writeName = new File(fileName);
            writeName.createNewFile();
            try (FileWriter writer = new FileWriter(writeName, true);
                 BufferedWriter out = new BufferedWriter(writer)){
                for(Map.Entry<String,String> entry:data.entrySet()) {
                    String key=entry.getKey().trim();
                    String value=entry.getValue().trim();
                    if(!keyValueMap.containsKey(key)) {
                        out.write(key+"="+value);
                        out.newLine();   // 换行
                    }
                }
                out.flush();
                keyValueMap.putAll(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String readFileString(String fileName) throws IOException {
        File file=new File(fileName);
        if(!file.exists()){
            return null;
        }
        try(BufferedReader in = new BufferedReader(new FileReader(file))) {
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
            return sb.toString();
        }
    }
    public static Map<String,String> readFileMap(String fileName) {
        Map<String,String> result=new HashMap<>();
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                return result;
            }
            try(BufferedReader  in = new BufferedReader(new FileReader(file))) {
                String str;
                while ((str = in.readLine()) != null) {
                    if(str!=null&&!"".equals(str.trim())) {
                        String key = str.split("=")[0];
                        String value = str.split("=")[1];
                        result.put(key.trim(), value.trim());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    private  String printThrowable(Throwable e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
    private void checkVersion(Stage primaryStage){
        String newVersion=YapiUtil.getVersion();
        if(!isNewVersion(version,newVersion)){
            Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("版本更新");
            alert.setHeaderText("当前版本号"+version+",最新版本号"+newVersion+",建议您更新程序");
            alert.setContentText("是否更新?");
            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == ButtonType.OK){
                Group root = new Group();
                Scene scene = new Scene(root, 220, 50);
                primaryStage.setScene(scene);
                primaryStage.setTitle("下载进度");
                final Label label = new Label();
                label.setText("进度:");
                final ProgressBar pb = new ProgressBar();
                //pb.setProgress(values[i]);
                final ProgressIndicator pin = new ProgressIndicator();
                //pin.setProgress(values[i]);
                final HBox hb  = new HBox();
                hb.setSpacing(1);
                hb.setAlignment(Pos.CENTER);
                hb.getChildren().addAll(label, pb, pin);
                final VBox vb = new VBox();
                vb.setSpacing(1);
                vb.getChildren().add(hb);
                scene.setRoot(vb);
                primaryStage.show();
                YapiUtil.downloadYapi(pb,pin,version,newVersion,primaryStage);
            } else {
                // ... user chose CANCEL or closed the dialog
            }
            });
        }

    }

    private boolean isNewVersion(String version,String newVersion){
        String[] versions=version.split("\\.");
        String[] newVersions=newVersion.split("\\.");
        int length=versions.length;
        int lengthV=newVersions.length;
        int minLength=Math.min(length,lengthV);
        for(int i=0;i<minLength;i++){
            int o=Integer.valueOf(versions[i]);
            int n=Integer.valueOf(newVersions[i]);
            if(o<n){
                return false;
            }
            if(o>n){
                return true;
            }
        }
        return length>=lengthV?true:false;
    }
    public static void main(String[] args) {
        log.info("入参:"+Arrays.asList(args));
        Thread thread =new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(args!=null&&args.length>0) {
                File file = new File(args[0]);
                boolean res=file.delete();
            }
        });
        thread.start();
        launch(args);
    }
}